package com.frxuexi.shop.view

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.lib_base.entity.CartBean
import com.frxuexi.lib_base.entity.CreateOrderDetail
import com.frxuexi.lib_base.entity.CreateOrderReqBean
import com.frxuexi.lib_base.entity.CreateOrderRespBean
import com.frxuexi.lib_base.entity.GetPreOrderRespBean
import com.frxuexi.lib_base.entity.OrderDetail
import com.frxuexi.lib_base.entity.PreOrderReqBean
import com.frxuexi.lib_base.entity.PreOrderRespBean
import com.frxuexi.lib_base.http.RequestType
import com.frxuexi.lib_base.mvi.BaseFragment
import com.frxuexi.lib_base.mvi.UiState
import com.frxuexi.lib_base.utils.ArouterManager
import com.frxuexi.shop.R
import com.frxuexi.shop.adapter.CartAdapter
import com.frxuexi.shop.databinding.FragmentCartBinding
import com.frxuexi.shop.intent.CartIntent
import com.frxuexi.shop.viewmodel.CartViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@AndroidEntryPoint
class CartFragment : BaseFragment<FragmentCartBinding,CartIntent,CartViewModel>() {
    override val binding: FragmentCartBinding by lazy { FragmentCartBinding.inflate(layoutInflater) }
    override val vm: CartViewModel by viewModels<CartViewModel>()
    val cartAdapter by lazy { CartAdapter() }
    var position=-1

    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect{
                when(it){
                    is UiState.onSuccess<*> ->{
                        when(it.type){
                            RequestType.DEFAULT->{
                                val bean = it.data as CartBean
                                cartAdapter.apply {
                                    data.clear()
                                    addData(bean.list)
                                    notifyDataSetChanged()
                                }
                                binding.cartNum.setText("购物车（${bean.list.size}）")
                            }
                            RequestType.UPDATE->{
                                cartAdapter.notifyItemChanged(position)
                            }
                            RequestType.DELETE->{
                                vm.sendIntent(CartIntent.getCarts(1))
                            }
                            RequestType.PREORDER->{
                                val bean = it.data as PreOrderRespBean
                                vm.sendIntent(CartIntent.getPreOrder(bean.preOrderNo))
                            }
                            RequestType.GET_PREORDER->{
                                val bean = it.data as GetPreOrderRespBean
                                val reqBean = CreateOrderReqBean(
                                    bean.orderInfoVo.addressId,
                                    bean.orderInfoVo.orderDetailList[0].attrValueId!!,
                                    bean.orderInfoVo.userCouponId,
                                    bean.orderInfoVo.remark?.toString()?:"",
                                    listOf(
                                        CreateOrderDetail(
                                            bean.orderInfoVo.addressId,
                                    bean.orderInfoVo.orderDetailList[0].attrValueId!!,
                                    bean.orderInfoVo.userCouponId,
                                    bean.orderInfoVo.remark?.toString()?:"",
                                    emptyList(),
                                    "alipay",
                                    "yue",
                                    bean.orderInfoVo.phone,
                                    bean.orderInfoVo.orderDetailList[0].productId!!,
                                    bean.orderInfoVo.orderProNum,
                                    bean.orderInfoVo.realName,
                                    1,
                                    0,
                                    false
                                )
                                    ),
                                    "alipay",
                                    "yue",
                                    bean.orderInfoVo.phone,
                                    bean.orderInfoVo.orderDetailList[0].productId!!,
                                    bean.orderInfoVo.orderProNum,
                                    bean.orderInfoVo.realName,
                                    1,
                                    0,
                                    false
                                )
                                vm.sendIntent(CartIntent.createOrder(reqBean))
                            }
                            RequestType.CREATE_ORDER->{
                                val bean = it.data as CreateOrderRespBean
                                ToastUtils.showLong("下单成功")
                                ArouterManager.nav(requireContext(),"/shop/OrderActivity")
                            }


                            else -> {}
                        }
                    }

                    else -> {}
                }
            }
        }
    }

    override fun initView() {
        binding.rvCar.apply {
            adapter=cartAdapter
            layoutManager=LinearLayoutManager(requireContext())
        }

        vm.sendIntent(CartIntent.getCarts(1))

        binding.cbAll.setOnClickListener {
            cartAdapter.data.forEach { it.checked= binding.cbAll.isChecked}
            cartAdapter.notifyDataSetChanged()
            binding.buyNow.setText("结算(${cartAdapter.data.count { it.checked }})")
            getSum()
        }

        cartAdapter.addChildClickViewIds(R.id.car_check_box,R.id.car_add,R.id.car_sub)
        cartAdapter.setOnItemChildClickListener { adapter, view, position ->
            val item = cartAdapter.data.get(position)
            this.position=position
            val cartNum = item.cartNum
            when(view.id){
                R.id.car_check_box->{
                    item.checked=!item.checked
                    binding.cbAll.isChecked=cartAdapter.data.all { it.checked }
                    binding.buyNow.setText("结算(${cartAdapter.data.count { it.checked }})")
                }
                R.id.car_add->{
                    if(cartNum+1<=item.stock){
                        item.cartNum=cartNum+1
                        vm.sendIntent(CartIntent.updateCart(item.id,cartNum+1))
                    }
                }
                R.id.car_sub->{
                    if(cartNum==1){
                        ToastUtils.showLong("购买数量不能小于1")
                        return@setOnItemChildClickListener
                    }
                    item.cartNum=cartNum-1
                    vm.sendIntent(CartIntent.updateCart(item.id,item.cartNum))
                }
            }
            getSum()
        }

        binding.cartDelete.setOnClickListener {
            val ids=cartAdapter.data.filter { it.checked }.map { it.id }
            vm.sendIntent(CartIntent.deleteCart(ids))
        }

        binding.buyNow.setOnClickListener {
            cartAdapter.data.filter { it.checked }.forEach {
                val preOrderBean = PreOrderReqBean(
                    preOrderType = "shoppingCart",
                    productId = it.productId,
                    shoppingCartId = it.id,
                    orderDetails = listOf<OrderDetail>(
                        OrderDetail(preOrderType = "shoppingCart",
                            productId = it.productId,
                            shoppingCartId = it.id)
                    )
                )
                vm.sendIntent(CartIntent.preOrder(preOrderBean))
            }

        }
    }

    fun getSum(){
        val sum=cartAdapter.data.filter { it.checked }.sumOf { it.cartNum*it.price.toDouble() }
        binding.amountAll.setText("合计：￥${sum}")
    }

}